import {DiffCalculation} from "./diff/diff-calculation";
import fs from "node:fs";
import {ProcessEventDerivation} from "./process/process-event-derivation";
import {readFile} from "node:fs/promises";
import {IEvent, MetadataResponse} from "./event-types";
import {glob} from "glob";



const files = ['../../Data/*/Derived/*.json' ];

const metadataFile = '../metadata.json'

// Read files
const readFiles = async (...patterns: string[]) => {
    const fileContents: {file: string, events: IEvent[]}[] = [];
    for (let pattern of patterns) {
        // find files with the given glob pattern
        const matchedFiles = await glob(pattern);
        for (let matchedFile of matchedFiles) {
            const displayEventsString = await readFile(matchedFile, {encoding: 'utf-8'});
            const events = <IEvent[]> JSON.parse(displayEventsString);
            fileContents.push({file: matchedFile, events});
        }

    }
    return fileContents;
}

// Calculate diff between display events
const diffCalculator = new DiffCalculation();
// Derive process events from the diff
const processEventDerivation = new ProcessEventDerivation();
readFiles(...files).then(result => {
    const metadata: MetadataResponse = JSON.parse(fs.readFileSync(metadataFile, {encoding: 'utf-8'}));
    for (let file of result) {
        const diffs = diffCalculator.calculateDiffBetweenDisplayEvents(file.events);
        const processEvents = processEventDerivation.deriveProcessEvents(file.events, diffs, metadata);
        fs.writeFileSync(file.file.replace('.json', '_diff.json'), JSON.stringify(diffs, undefined, 4));
        fs.writeFileSync(file.file.replace('.json', '_process.json'), JSON.stringify(processEvents, undefined, 4));
    }

});